/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.io.File;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImageUtils {

    static Logger logger = LoggerFactory.getLogger(ImageUtils.class);

    public static String copyFile(File fileToCopy) {
        File copyTo = getImagePath(fileToCopy);
        try {
            FileUtils.copyFile(fileToCopy, copyTo);
            logger.info("Success to copy file of " + fileToCopy.getAbsolutePath() + " to " + copyTo.getAbsolutePath());
            return copyTo.getAbsolutePath();
        } catch (IOException ex) {
            System.out.println("An error ocurred while copying the image file. Please try again");
            logger.error("Error while copying file of " + fileToCopy.getAbsolutePath() + " to " + copyTo.getAbsolutePath(), ex);
            return null;
        }
    }

    private static File getImagePath(File image) {
        File applicationImage = new File(System.getProperty("user.dir") + "\\src\\xml\\beer\\images\\" + image.getName());
        if (!applicationImage.exists()) {
            try {
                applicationImage.createNewFile();
            } catch (IOException ex) {
                logger.error("Error while trying to create a file " + applicationImage.getAbsolutePath(), ex);
            }
        } else {
            int cont = 1;
            while (applicationImage.exists()) {
                String filename = image.getName().substring(0, image.getName().lastIndexOf(".")) + "(" + cont + ")";
                String extension = image.getName().substring(image.getName().lastIndexOf("."), image.getName().length());
                String newfilename = System.getProperty("user.dir") + "\\src\\xml\\images\\beer\\" + filename + extension;
                applicationImage = new File(newfilename);
                cont++;
            }
        }
        return applicationImage;
    }

    public static String validateIsImageAndExists(File image) {
        if (!image.exists()) {
            return "The image doesn't exists. Please inform a valid image file";
        } else if (!validateImageExtension(image)) {
            return "The file informed for image it isn't a image. Please inform a image file";
        }
        return null;
    }
    
    private static boolean validateImageExtension(File image) {
        Pattern pattern = Pattern.compile("([^\\s]+(\\.(?i)(/bmp|jpe?g|gif|png))$)");
        Matcher matcher = pattern.matcher(image.getName());
        return matcher.matches();
    }
}
